package com.robot.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.robot.manager.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
class ManagerFilter extends ZuulFilter {
    private final Logger logger= LoggerFactory.getLogger(this.getClass());
    @Autowired
    private JwtUtil jwtUtil;

    /**在请求前pre或者后post执行*/
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 多个过滤器时的执行顺序，数字越小，表示越先执行
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**当前过滤器是否开启,true表示开启*/
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     *  过滤器内执行的操作
     * @return return 任何ojbect的值都表示继续执行
     *      set send zull Response(false)表示不再继续执行
     */
    @Override
    public Object run() {
        logger.info("request manager filter");
        RequestContext requestContext = RequestContext.getCurrentContext();

        //request域
        HttpServletRequest request = requestContext.getRequest();
        //预请求里没有Authorization等字段,所以要放行
        String option = "OPTIONS";

        if (request.getMethod().equals(option)) {
            logger.info("get an options request");
            return null;
        }

        //登录里没有Authorization等字段,所以要放行
        String login = "login";
        if (request.getRequestURI().indexOf(login) > 0) {
            logger.info("get a login request");
            return null;
        }
        String sms="sendSms";
        if (request.getRequestURI().indexOf(sms)>0) {
            logger.info("get a send sms request");
            return null;
        }

        //得到头信息
        String header = request.getHeader("AUTH");
        logger.info("AUTH:"+header);
        if (header != null && !"".equals(header)) {
            logger.info("get an Authorization");
            String firstString = "ROBOT ";
            if (header.startsWith(firstString)) {
                String token = header.substring(6);
                logger.info("token="+token);
                try {
                    Claims claims = jwtUtil.parseJwt(token);
                    String roles = (String) claims.get("roles");
                    String admin = "admin";
                    if (admin.equals(roles)) {
                        logger.info("get an admin role");
                        //把头信息转发下去，并且放行
                        requestContext.addZuulRequestHeader("AUTH", header);
                        return null;
                    }
                } catch (Exception e) {
                    logger.info("get a filter exception");
                    e.printStackTrace();
                    requestContext.setSendZuulResponse(false);
                }
            }
        }
        logger.info("request headers checked");

        requestContext.setSendZuulResponse(false);
        logger.info("zuul response set");

        requestContext.setResponseStatusCode(403);
        logger.info("response code set");

        requestContext.setResponseBody("{\"flag\":false,\"code\":20001,\"message\":\"权限不足\",\"data\":null}");
        logger.info("response body set");

        requestContext.getResponse().setContentType("application/json;charset=utf-8");
        logger.info("response content type set");

        logger.info("manager filer passed");

        return null;
    }
}